# -*- coding: utf-8 -*-
"""
@Time ： 2022/12/30 21:53
@Author ： PJC
"""
import json
import pprint
import configparser
from typing import Optional
from api.client import HttpClient
from common.read_yaml import get_yaml
from common.read_config import Environ, configpath
from common.route import login
import requests

data_ = get_yaml(Environ=Environ)
# print(data_['lisi'])
# print(login['url'], login['method'])

client_ = HttpClient()


# print(client_.get_full_url(login['url']))


def login_login(url: Optional[str] = None, body: Optional[dict] = None, headers: Optional[dict] = None):
    default_header = {
        "Content-Type": "application/json"
    }
    if not headers:
        headers = default_header
    result = requests.post(url, params=body, headers=headers)
    return result.json()


def login_token(unsename):
    body = data_[unsename]
    url = login['url']
    method = login['method']
    full_url = client_.get_full_url(url)
    # result = login_login(full_url, body=body)
    result = client_.send(full_url, body=body, method='get')
    # print(result)
    # assert result['code'] == 200, f"账号{unsename}登录失败"
    assert result['state'] == 1, f"账号{unsename}登录失败"
    token = result['content']['access_token']
    # 把token写入配置文件
    config = configparser.ConfigParser()
    config.read(configpath, encoding='utf-8-sig')
    # 配置文件中设置token的值
    config.set('token', f'{unsename}' + '_token', str(token))
    # 修改配置文件的类容并保存
    config.write(open(configpath, 'w'))
    return token


if __name__ == "__main__":
    print(login_token('lisi'))
    print(login_token('maji'))
